package com.yanjiali.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanjiali.entity.Collect;
import com.yanjiali.entity.SecondLevelCollect;
import com.yanjiali.mapper.SecondLevelCollectMapper;
import com.yanjiali.model.R;
import com.yanjiali.model.resp.GetSecondLevelCollectListByIdResp;
import com.yanjiali.service.CollectService;
import com.yanjiali.service.SecondLevelCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @Package: com.yanjiali.service.impl
* @Author: yanjiali
* @Created: 2025/4/26 19:43
*/
@Service
public class SecondLevelCollectServiceImpl extends ServiceImpl<SecondLevelCollectMapper, SecondLevelCollect> implements SecondLevelCollectService {

    @Autowired
    private CollectService collectService;

    @Override
    public R<GetSecondLevelCollectListByIdResp> getSecondLevelCollectListByName(String oneDirName) {
        LambdaQueryWrapper<Collect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Collect::getName, oneDirName);

        Collect collect = collectService.getOne(lambdaQueryWrapper);
        if(collect == null) {
            throw new IllegalArgumentException("不合法的一级收藏加名");
        }

        Long oneDirId = collect.getId();
        //获取登录用户的id
        String userId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            userId = authentication.getPrincipal().toString();
        }else {
            throw new RuntimeException("用户未登录");
        }

        LambdaQueryWrapper<SecondLevelCollect> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SecondLevelCollect::getCollectId, oneDirId)
                .eq(SecondLevelCollect::getUserId, userId)
                .or()
                .eq(SecondLevelCollect::getCollectId, oneDirId)
                .isNull(SecondLevelCollect::getUserId);

        List<SecondLevelCollect> list = list(lqw);

        if(list != null && list.size() > 0) {
            return R.ok(new GetSecondLevelCollectListByIdResp(list));
        }

        return R.fail("获取二级收藏夹失败");
    }
}
